package Service

import (
	"TCPServer/Interfaces"
	"fmt"
	"net"
)

type Server struct {
	IPVersion  string
	IP         string
	Port       int
	MsgHandler Interfaces.IMessageHandler
}

func NewServer(ip string, port int) *Server {
	s := &Server{
		IPVersion:  "tcp4",
		IP:         ip,
		Port:       port,
		MsgHandler: NewMessageHandler(),
	}
	NewMySQLConn()
	return s
}

func CallbackToClient(conn *net.TCPConn, b []byte, cnt int) error {
	if _, err := conn.Write(b[:cnt]); err != nil {
		return err
	}
	return nil
}

func (s *Server) Start() {
	go func() {
		s.MsgHandler.StartTaskQueue()
		addr, err := net.ResolveTCPAddr(s.IPVersion, fmt.Sprintf("%s:%d", s.IP,
			s.Port))
		if err != nil {
			fmt.Println("resolve tcp addr err: ", err)
			return
		}
		listenner, err := net.ListenTCP(s.IPVersion, addr)
		if err != nil {
			fmt.Println("listen", s.IPVersion, "err", err)
			return
		}
		var cid uint16
		cid = 0
		for {
			conn, err := listenner.AcceptTCP()
			if err != nil {
				fmt.Println("Accept err ", err)
				continue
			}
			dealConn := NewConnection(conn, cid, s.MsgHandler)
			cid++
			go dealConn.Start()
		}
	}()
}

func (s *Server) Stop() {}

func (s *Server) AddRouter(msgID uint16, router Interfaces.IRouter) {
	s.MsgHandler.AddRouter(msgID, router)
}
